package pro.cherish.knowledgeweb.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import pro.cherish.knowledgecmomon.annotation.NoAuthLogin;
import pro.cherish.knowledgecmomon.entity.BaseException;
import pro.cherish.knowledgecmomon.enums.BasicError;
import pro.cherish.knowledgeruntime.web.interceptor.WebInterceptor;
import pro.cherish.knowledgeruntime.web.session.CommonSession;
import pro.cherish.knowledgeruntime.web.session.ISessionService;
import pro.cherish.knowledgeruntime.web.session.TokenManager;
import pro.cherish.knowledgeutil.str.StringUtilExt;
import pro.cherish.knowledgeweb.constant.CommonConstant;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 创建人：cherish
 * @version 版本号：V1.0
 * <p>
 * ***************************修订记录************************************
 * 2019-11-03 cherish 创建该类功能。
 * **********************************************************************
 * </p>
 * @ClassName 类名：AuthInterceptor
 * @Description 功能说明：用户登入验证拦截器
 * <p>
 * TODO
 * </p>
 * **********************************************************************
 * @date 创建日期： 2019-11-03 cherish
 */
@Slf4j
@Component
public class AuthInterceptor implements WebInterceptor {

    @Autowired
    private ISessionService sessionService;

    public static final String TOKEN_FLAG = CommonConstant.TOKEN_FLAG;

    @Value("#{'${spring.profiles.active}' == 'dev'}")
    public boolean isDebug = false;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        NoAuthLogin nologinAnnotation;
//		if (isDebug) {
//			return true ;
//		}
        if (handler instanceof HandlerMethod) {
            nologinAnnotation = ((HandlerMethod) handler).getMethodAnnotation(NoAuthLogin.class);
        } else {
            return true;
        }
        // 携带@NoAuthLogin，无需登录校验
        if (nologinAnnotation != null) {
            return true;
        }
        // 菜单权限判断待补充
        String token = getToken(request, response);
        CommonSession commonSession = sessionService.get(token);
        if (commonSession == null) {
            log.error("缓存中token不存在或者已过期");
            throw BasicError.SESSION_TIMEOUT.toException();
        }
        // 重置过期时间
        sessionService.set(commonSession);
        // 设置会话到系统上下文
        TokenManager.putSession(commonSession);
        return true;
    }

    /**
     * 获取TOKEN
     *
     * @param httpServletRequest 请求
     * @param response           响应
     * @return
     * @throws BaseException
     */
    private String getToken(HttpServletRequest httpServletRequest, HttpServletResponse response) throws BaseException {
        String token = httpServletRequest.getParameter(TOKEN_FLAG);
        if (StringUtilExt.isEmpty(token)) {
            Cookie[] cookies = httpServletRequest.getCookies();
            if (cookies == null) {
                throw BasicError.NO_LOGIN.toException();
            }
            for (Cookie cookie : cookies) {
                if (TOKEN_FLAG.equals(cookie.getName())) {
                    token = cookie.getValue();
                    break;
                }
            }
            if (StringUtilExt.isBlank(token)) {
                log.error("该请求不存在token");
                throw BasicError.NO_LOGIN.toException();
            }
        }
        return token;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        TokenManager.removeSession();
    }

    @Override
    public int order() {
        return 0;
    }

    @Override
    public String[] patternUrl() {
        return new String[]{"/api/**", "/system/**", "/basic/**"};
    }
}

